package com.yhthu.query;

import com.yhthu.bean.Instruction;
import com.yhthu.bean.Record;
import com.yhthu.texthandler.BaseHandler;
import com.yhthu.texthandler.QueryParamHandler;
import com.yhthu.splitstrategy.SemicolonSpliter;
import com.yhthu.splitstrategy.SpaceSpliter;

import java.util.List;

public class Update extends BaseQuery {

    @Override
    public List<Record> getQueryReport(List<Record> sourceRecords, List<Instruction> instructionList) {
        List<Record> updatedRecordList = sourceRecords;
        for (Instruction instruction : instructionList) {
            String params = instruction.getParameters();
            BaseHandler<Record> queryParamSpliter = new QueryParamHandler();
            queryParamSpliter.setLineSplitStrategy(new SemicolonSpliter());
            queryParamSpliter.setWordSplitStrategy(new SpaceSpliter());
            List<Record> newRecordList = queryParamSpliter.getValidObjectFromTextContent(params);
            updateRecordList(updatedRecordList, newRecordList);
        }
        return updatedRecordList;
    }

    private void updateRecordList(List<Record> updatedRecordList, List<Record> newRecordList) {
        for (Record record : newRecordList) {
            int index = updatedRecordList.indexOf(record);
            if (index >= 0) {
                updatedRecordList.set(index, record);
            } else {
                updatedRecordList.add(record);
            }
        }
    }
}
